# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

import datetime
import logging

from dateutil.relativedelta import relativedelta
from odoo import api, fields, models

from . import tools

_logger = logging.getLogger(__name__)

RESP_COUNT_10 = 2


class CrSafetyScoreInputType(models.Model):
    _name = "cr.safety.score.input.type"
    _description = "cr.safety.score.input.type"

    name = fields.Char()
    code = fields.Char()
    type = fields.Selection([
        ('plus', '加分项目'),
        ('minus', '减分项目'),
        ('clear', '否决项目')], default='plus')
    is_auto = fields.Boolean()

    is_used = fields.Boolean()
    item_ids = fields.One2many('cr.safety.score.item', 'input_type_id')




class CrSafetyScoreInputRole(models.Model):
    _name = "cr.safety.score.input.role"
    _description = "cr.safety.score.input.role"

    name = fields.Char()
    code = fields.Char()


class CrSafetyScoreInput(models.Model):
    _name = "cr.safety.score.input"
    _description = "cr.safety.score.input"

    name = fields.Char()
    date = fields.Date('date')
    date_month = fields.Date('date_month')
    date_month_name = fields.Char('date_month_name', compute='_compute_date_month')

    @api.depends('date_month')
    def _compute_date_month(self):
        for rec in self:
            rec.date_month_name = datetime.datetime.strftime(rec.date_month, "%Y-%m")

    input_type_id = fields.Many2one('cr.safety.score.input.type', 'input_type_id', )

    input_type_type = fields.Selection([
        ('plus', '加分项目'),
        ('minus', '减分项目'),
        ('clear', '否决项目')], related='input_type_id.type')

    resp_sheet_id = fields.Many2one('cr.safety.resp.sheet', 'resp_sheet_id')
    quantity = fields.Integer(default=1)

    item_ids = fields.One2many('cr.safety.score.item', related='input_type_id.item_ids')

    # 业务对象 可能是 职工 干部 科室 车间
    employee_id = fields.Many2one('hr.employee', 'employee_id', help='本人')
    employee_name = fields.Char('employee_name', related='employee_id.name')
    employee_barcode = fields.Char('employee_barcode', related='employee_id.barcode')
    emp_department_id = fields.Many2one('hr.department', 'emp_department_id', related='employee_id.department_id')
    department_id = fields.Many2one('hr.department', 'department_id', )

    parent_id = fields.Many2one('hr.employee', 'parent_id', help='主管干部')
    parent2_id = fields.Many2one('hr.employee', 'parent2_id', help='主管干部2')
    manager_id = fields.Many2one('hr.employee', 'manager_id')
    manager2_id = fields.Many2one('hr.employee', 'manager2_id')

    line_ids = fields.One2many('cr.safety.score.line', 'input_id')

    @api.depends('employee_id', 'department_id')
    def _compute_manager(self):
        for rec in self:

            # print('123456789, rec.employee_id', rec.employee_id)
            # print('123456789, rec.employee_id.department_id', rec.employee_id.department_id)
            # print('123456789, rec.employee_id.department_id.manager_id', rec.employee_id.department_id.manager_id)
            # print('123456789, rec.department_id', rec.department_id)
            # print('123456789, rec.department_id.manager_id', rec.department_id.manager_id)

            if rec.employee_id:
                department_id = rec.employee_id.department_id
            elif rec.department_id:
                department_id = rec.department_id
            else:
                department_id = self.env['hr.department']

            if department_id:
                rec.manager_id = department_id.manager_id
            else:
                rec.manager_id = self.env['hr.employee']

    # TBDCODE 由责任清单 创建的 积分输入, 不能重复创建，先查找删除旧的
    @api.model
    def create(self, values):
        def get_types_by_code(codes):
            obj = self.env['cr.safety.score.input.type']
            return obj.search([['code','in', codes]]).ids

        employee_id = values.get('employee_id')
        date_month = values.get('date_month')
        date_month = datetime.datetime.strptime(date_month, '%Y-%m-%d')
        date_month = datetime.datetime.strftime(date_month, "%Y-%m") + '-01'

        input_type_id = values.get('input_type_id')


        # 2020-6-7 get id by code
        type_ids = get_types_by_code(['n1007', 'n2038', '2039'])

        # TBD 如果是 责任清单考评过来的，则判断 同一份责任清单 只有一个考评结果
        # TBDCODE = n1007, n2038, 2039
        # if input_type_id in (51,96,97):
        if input_type_id in type_ids:
            # 2020-6-7 get id by code
            domain = [
                ('employee_id', '=', employee_id),
                ('date_month', '=', date_month),
                # 2020-6-7 get id by code
                ('input_type_id', 'in', type_ids),
                # ('input_type_id', 'in', [51,96,97]),
                # 2020-6-7 get id by code
            ]

            resp_res = self.search(domain)
            # _logger.info()
            if resp_res:
                resp_res.unlink()
        # 不同考评结果 分数不一样

        domain = [
            ('employee_id', '=', employee_id),
            ('date_month', '=', date_month),
            ('input_type_id', '=', input_type_id),
        ]

        res = self.search(domain, limit=1)
        if res:
            quantity = values.get('quantity', None)
            if quantity != None:
                res.write({'quantity': quantity})
            return res

        values['date_month'] = date_month
        return super(CrSafetyScoreInput, self).create(values)


    def unlink(self):
        self.line_ids.unlink()
        return super(CrSafetyScoreInput, self).unlink()

    def write(self, values):
        self.line_ids.unlink()
        return super(CrSafetyScoreInput, self).write(values)

    # TBDCODE  积分类型  
    @api.model
    def import_card(self, values):

        res = []
        d_emps = []
        for i in values:
            _logger.info(i)
            input_types = self.get_input_type_id(i)
            input_type = input_types[0]
            input_type_id = input_types[1]
            date_month = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m") + '-01'
            if input_type == 1:
                employee = self.env['hr.employee'].search([('barcode', '=', i['manager_code'])])
                _logger.info(employee)
                employee_id = employee[0].id
                parent = self.env['hr.employee'].search([('barcode', '=', i['leader_code'])])
                parent_id = parent[0].id
                _logger.info(date_month)
                cv = {
                    'employee_id': employee_id,
                    'date_month': date_month,
                    'input_type_type': 'minus',
                    'input_type_id': input_type_id,
                    'parent_id': parent_id,
                }
                rec = self.create(cv)
                rec.action_done()
                res.append(rec.read())
            elif input_type == 2:
                employee = self.env['hr.employee'].search([('barcode', '=', i['manager_code'])])
                _logger.info(employee)
                employee_id = employee[0].id
                # parent = self.env['hr.employee'].search([('barcode', '=', i['leader_code'])])
                # parent_id = parent[0].id
                _logger.info(date_month)
                cv = {
                    'employee_id': employee_id,
                    'date_month': date_month,
                    'input_type_type': 'minus',
                    'input_type_id': input_type_id,
                    # 'parent_id': parent_id,
                }
                rec = self.create(cv)
                rec.action_done()
                res.append(rec.read())
            elif input_type == 3:
                employee = self.env['hr.employee'].search([('barcode', '=', i['manager_code'])])
                _logger.info(employee)
                employee_id = employee[0].id
                parent = self.env['hr.employee'].search([('barcode', '=', i['leader_code'])])
                parent_id = parent[0].id
                _logger.info(date_month)
                cv = {
                    'employee_id': employee_id,
                    'date_month': date_month,
                    'input_type_type': 'minus',
                    'input_type_id': input_type_id,
                    'parent_id': parent_id,
                }
                rec = self.create(cv)
                rec.action_done()
                res.append(rec.read())
            elif input_type == 4:
                employee = self.env['hr.employee'].search([('barcode', '=', i['employee_code'])])
                _logger.info(employee)
                employee_id = employee[0].id
                d_emps.append(employee_id)
                resp = self.env['cr.safety.resp.sheet'].search([('employee_id.id','=',employee_id),('date_month','=',date_month)])
                if len(resp)>0:
                    resp.action_done2('D','受到车站红牌,考评为不称职')
                    res.append(str(employee_id)+'=D')
                else:
                    resp = self.env['cr.safety.resp.sheet'].create({'employee_id':employee_id,'date_month':date_month})
                    resp.action_done2('D','受到车站红牌,考评为不称职')
                    res.append(str(employee_id)+'=D')
            elif input_type == 5:
                employee = self.env['hr.employee'].search([('barcode', '=', i['employee_code'])])
                _logger.info(employee)
                employee_id = employee[0].id
                if employee_id in d_emps:
                    res.append(str(employee_id)+'is D ')
                else:
                    resp = self.env['cr.safety.resp.sheet'].search([('employee_id.id','=',employee_id),('date_month','=',date_month)])
                    if len(resp)>0:
                        resp.action_done2('C','受到车站黄牌,考评为基本称职')
                        res.append(str(employee_id)+'=C')
                    else:
                        resp = self.env['cr.safety.resp.sheet'].create(
                            {'employee_id': employee_id, 'date_month': date_month})
                        resp.action_done2('C', '受到车站黄牌,考评为基本称职')
                        res.append(str(employee_id)+'=C')
            else:
                cv={}
            _logger.info(str(cv))
            # self.create({
            #     'employee_id':employee_id
            # 'date_month':date_month
            # 'input_type_type': 'minus'
            #   'input_type_id':input_type_id
            # 'parent_id': 159
            # })
        return res

    # TBDCODE  被 import_card 调用
    # 32,safety_score_input_type_2121,minus,2121,受集团公司红牌(苗子)
    # 33,safety_score_input_type_2123,minus,2123,受集团公司黄牌
    # 34,safety_score_input_type_2131,minus,2131,受车站红牌(苗子)

    # ????? 4,5 是什么
    # 4, safety_score_input_type_1022,plus,1022,干部责任清单考核为称职
    # 5, safety_score_input_type_1031,plus,1031,干部责任清单交办责任完成超过3项

    def get_input_type_id(self, values):
        level = values['level']
        type = values['type']
        employee_type = values['employee_type']
        if level == '集团公司' and type == '红牌':
            input_type = 1
            input_type_id = 32
        elif level == '集团公司' and type == '黄牌':
            input_type = 2
            input_type_id = 33
        elif level == '车站' and type == '红牌' and employee_type == '工人':
            input_type = 3
            input_type_id = 34
        elif level == '车站' and type == '红牌' and employee_type == '干部':
            input_type = 4
            input_type_id = 4
        elif level == '车站' and type == '黄牌' and employee_type == '干部':
            input_type = 5
            input_type_id = 5
        return input_type, input_type_id

    # 将积分输入 写入  积分明细
    def action_done(self):
        for rec in self:
            for item in rec.item_ids:
                role_code = item.input_role_code
                emp = None
                if role_code == 'employee':
                    emp = [rec.employee_id]
                elif role_code == 'parent':
                    emp = [rec.parent_id,rec.parent2_id]
                elif role_code == 'manager':
                    emp = [rec.manager_id,rec.manager2_id]

                elif role_code == 'all_dept':
                    emp = rec.department_id.member_ids

                elif role_code == 'all':
                    emp = self.env['hr.employee'].search([['id', '!=', 1]])

                print('score input done 1,', emp)

                if emp:
                    date_month = fields.Date.to_string(rec.date_month)

                    for emp_one in emp:
                        print('score input done emp_one ,', emp_one)
                        if emp_one:
                            sheet = self.env['cr.safety.score.sheet'].create({
                                'date_month': date_month,
                                'employee_id': emp_one.id,
                                # 'resp_sheet_id': rec.resp_sheet_id
                            })

                            print('score input done sheet ,', sheet)

                            self.env['cr.safety.score.line'].create({
                                'sheet_id': sheet.id,
                                'input_id': rec.id,
                                'item_id': item.id,
                                'quantity': rec.quantity,
                                'name': rec.name,
                                'state': 'done'
                            })

        return True




class CrSafetyScoreItem(models.Model):
    _name = "cr.safety.score.item"
    _description = "cr.safety.score.item"

    input_type_id = fields.Many2one('cr.safety.score.input.type', 'input_type_id', ondelete='restrict')
    input_role_id = fields.Many2one('cr.safety.score.input.role', 'input_role_id', ondelete='restrict')
    input_role_code = fields.Char('input_role_code', related='input_role_id.code')

    name = fields.Char()
    code = fields.Char()
    job_type = fields.Selection([
        ('staff', '职工'),
        ('manager', '干部')], default='manager')
    type = fields.Selection([
        ('plus', '加分项目'),
        ('minus', '减分项目'),
        ('clear', '否决项目')], default='plus')

    type2 = fields.Selection([
        ('byme', '自控问题'),
        ('byother', '他控问题'),
        ('byorg', '检查问题')], default='byme')

    score = fields.Integer()
    score_name = fields.Char(compute='_compute_name')
    display_name = fields.Char(compute='_compute_name')

    @api.depends('score', 'name')
    def _compute_name(self):
        for rec in self:
            score_name = rec.score > 0 and '+' + str(rec.score) or str(rec.score)
            rec.score_name = score_name
            rec.display_name = "(%s)%s" % (score_name, rec.name)


class CrSafetyScoreLine(models.Model):
    _name = "cr.safety.score.line"
    _description = "cr.safety.score.line"

    name = fields.Char()
    state = fields.Selection([
        ('todo', '未审核'),
        ('doing', '未通过'),
        ('done', '已审核')], default='todo')

    item_id = fields.Many2one('cr.safety.score.item', 'item_id', ondelete='restrict')

    item_type = fields.Selection([
        ('plus', '加分项目'),
        ('minus', '减分项目'),
        ('clear', '否决项目')], related='item_id.type')

    item_name = fields.Char('item_name', related='item_id.display_name')
    score_unit = fields.Integer('score_unit', related='item_id.score')
    quantity = fields.Integer(default=1)
    score = fields.Integer(compute='_compute_score')

    @api.depends('score_unit', 'quantity')
    def _compute_score(self):
        for rec in self:
            rec.score = rec.score_unit * rec.quantity

    input_id = fields.Many2one('cr.safety.score.input', 'input_id', ondelete='cascade')

    sheet_id = fields.Many2one('cr.safety.score.sheet', 'sheet_id', ondelete='cascade')
    date_month = fields.Date('date_month', related='sheet_id.date_month')
    date_month_name = fields.Char('date_month_name', related='sheet_id.date_month_name')

    employee_id = fields.Many2one('hr.employee', 'employee_id', related='sheet_id.employee_id')
    employee_name = fields.Char('employee_name', related='employee_id.name')
    employee_barcode = fields.Char('employee_barcode', related='employee_id.barcode')

    @api.model
    def create(self, values):
        sheet_id = values.get('sheet_id')
        input_id = values.get('input_id')
        item_id = values.get('item_id')

        domain = [
            ['sheet_id', '=', sheet_id],
            ['input_id', '=', input_id],
            ['item_id', '=', item_id],
        ]

        rec = self.search(domain, limit=1)
        if not rec:
            rec = super(CrSafetyScoreLine, self).create(values)

        rec.to_update_sheet()
        return rec

    def write(self, values):
        ret = super(CrSafetyScoreLine, self).write(values)
        self.to_update_sheet()
        return ret

    def unlink(self):
        sheet_id = self.mapped('sheet_id')
        ret = super(CrSafetyScoreLine, self).unlink()
        self.to_update_sheet(sheet_id)
        return ret

    def to_update_sheet(self, sheet_id=None):
        sheet_id = sheet_id or self.sheet_id
        for rec in sheet_id:
            rec.update_me()


class CrSafetyScoreSheet(models.Model):
    _name = "cr.safety.score.sheet"
    _description = "cr.safety.score.sheet"

    name = fields.Char()

    date_month = fields.Date('date_month')
    date_month_name = fields.Char('date_month_name', compute='_compute_date_month')
    quarter_key = fields.Integer('quarter_key')
    year = fields.Integer('year')
    quarter = fields.Integer('quarter')
    is_last_month_of_quarter = fields.Boolean('is_last_month_of_quarter')

    @api.depends('date_month')
    def _compute_date_month(self):
        for rec in self:
            rec.date_month_name = datetime.datetime.strftime(rec.date_month, "%Y-%m")

    department_id = fields.Many2one(
        'hr.department', 'department_id',
        related='employee_id.department_id', store=True)
    department_group_id = fields.Many2one(
        'cr.safety.hr.dept.group', 'department_group_id',
        related='employee_id.department_group_id', store=True)

    employee_id = fields.Many2one('hr.employee', 'employee_id')
    employee_name = fields.Char('employee_name', related='employee_id.name')
    employee_barcode = fields.Char('employee_barcode', related='employee_id.barcode')
    employee_job_type = fields.Selection([
        ('staff', '职工'),
        ('manager', '干部')], related='employee_id.job_type')

    employee_job_id = fields.Many2one('hr.job', 'employee_job_id', related='employee_id.job_id')

    line_ids = fields.One2many('cr.safety.score.line', 'sheet_id')

    base_score = fields.Integer(default=100)
    plus_score = fields.Integer(default=0)
    minus_score = fields.Integer(default=0)
    clear_flag = fields.Integer(default=0)
    total = fields.Integer(default=100)
    check_result = fields.Selection([
        ('S', '待评估'),
        ('A', '优秀'),
        ('B', '合格'),
        ('C', '失信')], default='A')

    # 组内排名,科室内排名, 在 line_ids 创建和修改时进行计算
    rank_by_group = fields.Integer(default=1)
    rank_by_dept = fields.Integer(default=1)

    resp_no_duty_count = fields.Integer(default=0)
    is_month_star = fields.Boolean(default=False)
    is_last2_month_star = fields.Boolean(default=False)
    is_last_month_star = fields.Boolean(default=False)

    is_quarter_star = fields.Boolean(default=False)

    is_last2_quarter_star = fields.Boolean()
    is_last_quarter_star = fields.Boolean()

    is_tri_quarter_star = fields.Boolean()

    state = fields.Selection([
        ('todo', '未审核'),
        ('doing', '审核中'),
        ('done', '已审核')], compute='_compute_state', inverse='_inverse_state')

    @api.depends('line_ids.state')
    def _compute_state(self):
        for rec in self:
            line_states = rec.line_ids.mapped('state')
            todos = len(list(filter(lambda item: item == 'todo', line_states)))
            doings = len(list(filter(lambda item: item == 'doing', line_states)))
            dones = len(list(filter(lambda item: item == 'done', line_states)))

            rec.state = doings and 'doing' or (
                    not dones and 'todo' or (
                    not todos and 'done' or 'doing'))

    def _inverse_state(self):
        for rec in self:
            for line in rec.line_ids:
                line.state = rec.state

    def _update_other_date_field(self):
        year = self.date_month.year
        month = self.date_month.month
        quarter = ((month - 1) // 3) + 1
        self.year = year
        self.quarter = quarter
        self.quarter_key = year * 100 + quarter
        self.is_last_month_of_quarter = month in [3, 6, 9, 12]


    @api.model
    def create_init(self, values):
        date_month = values.get('date_month')
        date_month = datetime.datetime.strptime(date_month,'%Y-%m-%d')
        date_month = datetime.datetime.strftime(date_month, "%Y-%m") + '-01'

        emps = self.env['hr.employee'].search([])
        for emp in emps:
            employee_id = emp.id
            domain =[( 'employee_id','=', employee_id),
                ('date_month','=',date_month)
            ]

            res = self.search(domain,limit=1)
            if res:
                continue

            values['date_month'] = date_month
            rec = super(CrSafetyScoreSheet, self).create({
                'date_month': date_month,
                'employee_id': employee_id
            })
            rec.name = rec.date_month_name + ' ' + rec.employee_name
            rec._update_other_date_field()
            rec._compute_score()
            rec._update_rank()

    @api.model
    def create(self, values):
        self.create_init(values)
        rec = tools.find_or_create_for_emp_month(CrSafetyScoreSheet, self, values)
        rec.name = rec.date_month_name + ' ' + rec.employee_name
        rec._update_other_date_field()
        rec._compute_score()
        rec._update_rank()
        return rec

    def write(self, values):
        ret = tools.write_for_emp_month(CrSafetyScoreSheet, self, values)
        return ret

    def unlink(self):
        date_month = self.date_month
        department_group_id = self.department_group_id.id
        department_id = self.department_id.id

        ret = super(CrSafetyScoreSheet, self).unlink()
        self._update_rank(date_month, department_group_id, department_id)
        return ret

    def update_me(self):
        self._compute_score()
        self._update_month_star()
        self._update_quarter_star()
        self._update_tri_quarter_star()
        self._update_rank()
        self._update_lost_credit()

    def _compute_score(self):
        for rec in self:
            lines = rec.line_ids.filtered(lambda item: item.state == 'done')

            # lines = lines.mapped('score')
            plus = sum(lines.filtered(
                lambda item: item.score > 0).mapped('score'))
            minus = sum(lines.filtered(
                lambda item: item.score < 0).mapped('score'))
            clear = lines.filtered(lambda item: item.item_type == 'clear')
            total = not clear and plus + minus + 100 or 0
            total = total > 0 and total or 0

            level = rec.employee_job_type == 'manager' and {'A': 95, 'B': 80} or {'A': 90, 'B': 60}

            # todo_lines = rec.line_ids.filtered(lambda item: item.state == 'todo')

            check_result = total >= level['A'] and 'A' or (total >= level['B'] and 'B' or 'C')
            # if todo_lines:
            #     check_result = 'S'

            rec.base_score = 100
            rec.plus_score = plus
            rec.minus_score = minus
            rec.clear_flag = clear and 1 or 0
            rec.total = total
            rec.check_result = check_result

    # TBD 需要更新下个月 的上月星
    def _update_month_star(self):
        domain = [
            ['date_month', '=', self.date_month],
            ['employee_id', '=', self.employee_id.id]
        ]

        resp_sheet_id = self.env['cr.safety.resp.sheet'].search(domain, limit=1)
        lines = resp_sheet_id.line_ids.filtered(
            lambda line: line.type_code != 'duty' and line.state == 'done')
        resp_lines = lines
        if resp_lines:
            self.resp_no_duty_count = len(resp_lines)
        else:
            self.resp_no_duty_count = 0

        if self.check_result == 'A' and len(resp_lines) >= RESP_COUNT_10:
            self.is_month_star = True
        else:
            self.is_month_star = False

    def _update_quarter_star(self):
        def get_sheet(num):
            date_month = self.date_month.replace(day=1) + relativedelta(months=num)
            return self.search([
                ['employee_id', '=', self.employee_id.id],
                ['date_month', '=', date_month]], limit=1)

        last2_month_sheet_id = get_sheet(-2)
        last_month_sheet_id = get_sheet(-1)
        next_month_sheet_id = get_sheet(1)
        next2_month_sheet_id = get_sheet(2)

        sheets = [
            last2_month_sheet_id,
            last_month_sheet_id,
            self,
            next_month_sheet_id,
            next2_month_sheet_id
        ]

        sheets2 = [
            self,
            next_month_sheet_id,
            next2_month_sheet_id
        ]

        for index, sheet in enumerate(sheets2):
            if not sheet:
                continue

            last2 = sheets[index]
            last = sheets[index + 1]

            if last2 and last2.is_month_star:
                sheet.is_last2_month_star = True
            else:
                sheet.is_last2_month_star = False

            if last and last.is_month_star:
                sheet.is_last_month_star = True
            else:
                sheet.is_last_month_star = False

            if not sheet.is_last_month_of_quarter:
                continue

            if sheet.is_month_star and sheet.is_last2_month_star and sheet.is_last_month_star:
                sheet.is_quarter_star = True
            else:
                sheet.is_quarter_star = False

    def _update_tri_quarter_star(self):
        def _get_last_quarter_key(quarter_key):
            year = quarter_key // 100
            quarter = quarter_key % 100
            if quarter - 1:
                return year * 100 + quarter - 1
            else:
                return (year - 1) * 100 + 4

        def _get_next_quarter_key(quarter_key):
            year = quarter_key // 100
            quarter = quarter_key % 100
            if quarter + 1 == 5:
                return (year + 1) * 100 + 1
            else:
                return year * 100 + quarter + 1

        def get_sheet(last):
            return self.search([
                ['employee_id', '=', self.employee_id.id],
                ['is_last_month_of_quarter', '=', True],
                ['quarter_key', '=', last]], limit=1)

        last_quarter_key = _get_last_quarter_key(self.quarter_key)
        last2_quarter_key = _get_last_quarter_key(last_quarter_key)
        next_quarter_key = _get_next_quarter_key(self.quarter_key)
        next2_quarter_key = _get_next_quarter_key(next_quarter_key)

        last2_sheet = get_sheet(last2_quarter_key)
        last_sheet = get_sheet(last_quarter_key)
        me_sheet = get_sheet(self.quarter_key)
        next_sheet = get_sheet(next_quarter_key)
        next2_sheet = get_sheet(next2_quarter_key)

        sheets = [last2_sheet, last_sheet, me_sheet, next_sheet, next2_sheet]
        sheets2 = [me_sheet, next_sheet, next2_sheet]

        for index, sheet in enumerate(sheets2):
            if not sheet:
                continue

            last2 = sheets[index]
            last = sheets[index + 1]

            if last2 and last2.is_quarter_star:
                sheet.is_last2_quarter_star = True
            else:
                sheet.is_last2_quarter_star = False

            if last and last.is_quarter_star:
                sheet.is_last_quarter_star = True
            else:
                sheet.is_last_quarter_star = False

            if not sheet.is_last_month_of_quarter:
                continue

            if sheet.is_quarter_star and sheet.is_last2_quarter_star and sheet.is_last_quarter_star:
                sheet.is_tri_quarter_star = True
            else:
                sheet.is_tri_quarter_star = False

    def _update_rank(self, date_month=None, department_group_id=None, department_id=None):

        date_month = date_month or self.date_month
        department_group_id = department_group_id or self.department_group_id.id
        department_id = department_id or self.department_id.id

        order = 'total desc'
        domain = [
            ['date_month', '=', date_month],
            ['department_group_id', '=', department_group_id],
        ]

        obj = self.search(domain, order=order)

        last_rank = 1
        last_total = 0
        for index, rec in enumerate(obj):
            rec.rank_by_group = rec.total == last_total and last_rank or index + 1
            last_rank = rec.rank_by_group
            last_total = rec.total

        domain = [
            ['date_month', '=', date_month],
            ['department_id', '=', department_id],
        ]

        obj = self.search(domain, order=order)

        last_rank = 1
        last_total = 0
        for index, rec in enumerate(obj):
            rec.rank_by_dept = rec.total == last_total and last_rank or index + 1
            last_rank = rec.rank_by_dept
            last_total = rec.total

    # TBDCODE 积分更新失信, 失信类型, 
    def _update_lost_credit(self):

        if not self.clear_flag and self.check_result not in ['C']:
            return None

        if self.clear_flag:
            # 符合积分否决条件的, 直接失信
            type_id_ref = 'cr_safety.safety_lost_credit_type_1004'
        else:
            # 干部低于80, 失信
            type_id_ref = 'cr_safety.safety_lost_credit_type_1001'

        alert_obj = self.env['cr.safety.lost.credit']
        ret = alert_obj.find_or_create(
            self.date_month, self.employee_id.id, type_id_ref)

        return ret
